<template>
    <div class="index">
        <div class="search">
            <van-sticky>
                <van-search @search="onSearch" v-model="search_value" shape="round" background="rgb(239, 214, 209)" placeholder="请输入搜索关键词"/>
            </van-sticky>
        </div>
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <div class="banner">
                <van-swipe class="my-swipe" :autoplay="5000" indicator-color="white">
                    <van-swipe-item>
                        <img src="../../assets/banner.png" alt="" srcset="">
                    </van-swipe-item>
                    <van-swipe-item>
                        <img src="../../assets/banner.png" alt="" srcset="">
                    </van-swipe-item>
                </van-swipe>
            </div>
            <van-sticky :offset-top="50">
                <van-dropdown-menu >
                    <van-dropdown-item @change='changeMenu' v-model="good_stype" :options="option1" />
                    <van-dropdown-item @change='changeMenu' v-model="good_sort" :options="option2" />
                </van-dropdown-menu>
            </van-sticky>
            <van-skeleton title :row="3" :loading="loading">
                <div class="list" v-if="good_list.length>0">
                    <div class="item" v-for="item in good_list" :key='item.id' @click="itemClick(item.id)">
                        <van-card :price="Array.isArray(item.m_price)?Number(item.m_price[item.m_price.length-1].price):item.m_price" :origin-price="Array.isArray(item.m_price)?Number(item.m_price[item.m_price.length-1].price)+28:item.m_price+28" :desc="item.describe" :title="item.title" :thumb="item.logoUrl">
                            <template #tags>
                                <van-tag plain type="danger">会员优惠</van-tag>
                            </template>
                            <template #footer>
                                <div class="goodimg">
                                    <img :src="item.url" alt="">
                                </div>
                                <van-button round type="danger" size="small" @click.stop="sku_show(item.id)">立即抢购</van-button>
                            </template>
                        </van-card>
                    </div>
                </div>
                <van-empty
                    v-else
                    class="custom-image"
                    image="https://img.yzcdn.cn/vant/custom-empty-image.png"
                    description="暂无商品"
                />
            </van-skeleton>
            <van-popup position="bottom" v-model="show">
                <div class="popup">
                    <van-skeleton title :row="3" :loading="sku_loading" >
                        <div class="cont">
                            <div class="sku_header">
                                <div class="img">
                                    <img :src="curr_sku.url" alt="">
                                </div>
                                <div class="sku_goodsinfo">
                                    <div class="goods_price" v-if="Array.isArray(curr_sku.price)">
                                        <div class="goods_price_item" v-for="(item,index) in curr_sku.price" :key="index">
                                            <div v-if="index === curr_sku.price.length-1">
                                                <h3>{{item.price}}元</h3>
                                                <p>>={{item.num}}箱</p>
                                            </div>
                                            <div v-else-if="index ===0">
                                                <h3>{{item.price}}元</h3>
                                                <p>{{">="+item.num}}箱</p>
                                            </div>
                                            <div v-else>
                                                <h3>{{item.price}}元</h3>
                                                <p>>={{item.num}}箱</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="goods_price" v-else><span>{{curr_sku.price}}元</span></div>
                                    <div class="goods_item">库存：{{curr_sku.stock}}</div>
                                    <div class="goods_item">已选：{{curr_sku.name}}*{{curr_sku.count}}</div>
                                </div>
                            </div>
                            <div class="goods_body">
                                <div class="title">规格</div>
                                <div class="btm">
                                    <div class="item" :class="{current:item.id === skuId}" v-for="(item,index) in sku.sku_list" :key='index' @click="pickSku(index)">{{item.name}}</div>
                                </div>
                                <div class="goods_num">
                                    <div class="title">选择数量</div>
                                    <div class="stepper" v-if="Array.isArray(curr_sku.price)">
                                        <van-stepper v-model="curr_sku.count" :min="curr_sku.price[0].num" :max="Number(curr_sku.stock)" />
                                    </div>
                                    <div class="stepper" v-else>
                                        <van-stepper v-model="curr_sku.count" :min="1" :max="Number(curr_sku.stock)" />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="btm">
                            <van-goods-action>
                                <van-goods-action-icon @click="goShopCart" icon="cart-o"  text="购物车"/>
                                <van-goods-action-button :loading='btn_loading' type="warning" text="加入购物车" @click="shopcartAdd"/>
                                <van-goods-action-button :loading='btn_loading' type="danger" text="立即购买" @click="buy"/>
                            </van-goods-action>
                        </div>
                    </van-skeleton>
                </div>
            </van-popup>
        </van-pull-refresh>
        <van-tabbar route active-color="#ee0a24">
            <van-tabbar-item to="/" icon="shop-o">首页</van-tabbar-item>
            <van-tabbar-item to="/goodstypelist" icon="apps-o">全部分类</van-tabbar-item>
            <van-tabbar-item to="/shopcart" icon="shopping-cart-o">购物车</van-tabbar-item>
            <van-tabbar-item to="/center" icon="manager-o">会员中心</van-tabbar-item>
        </van-tabbar>
    </div>
</template>
<script>
import GetQueryString from "@/assets/js/getQueryString.js";
import { mapState } from "vuex";
export default {
    data(){
        return{
            show:false,//显示弹出层
            good_list:[],//商品列表
            search_value:null,//搜索关键字
            isLoading: false,//下拉刷新
            loading:true,//骨架屏
            sku_loading:true,//
            btn_loading:false,//按钮loading
            good_stype: '正在热卖',//当前选中分类
            good_sort: '-rise',//当前选中排序
            sku:{},
            curr_sku:{},//当前选中商品规格
            skuId:null,//当前选中规格商品id
            option1: [
                { text: '正在热卖', value: '正在热卖' },
                { text: '新品预热', value: '新品预热' }
            ],
            option2: [
                { text: '默认排序', value: '-rise' },
                { text: '销量排序', value: '-total' }
            ],
        }
    },
    computed:{
        ...mapState(["openid"]),
    },
    mounted(){
        // 测试用
        //localStorage.setItem('openId','osD2u5l_H4Xo1eUXD7goZ0JlUP2I') //Right.man
        //localStorage.setItem('openId', 'osD2u5rQjMkQMfKni_ffHwfjf3Eo') //Trouble
        localStorage.setItem('openId','osD2u5oEYUbbaCG3v4ZqJv0mnEqM') //Pupil
        this.login()
        
    },
    methods:{
        //搜索
        onSearch(){
            this.$router.push({ name: 'Search', params: { key: this.search_value }})

        },
        //点击购物车
        goShopCart(){
            this.$router.push('/shopcart')
        },
        //进入商品详情
        itemClick(e){
            this.$router.push({ path: `/goodsdetail/${e}` })
        },
        //选择规格
        pickSku(e){
            console.log('选择规格>>>>>>>>>>>>>',e)
            this.curr_sku = this.sku.sku_list[e]
            this.curr_sku.count = 1
            this.skuId = this.curr_sku.id

        },
        //点击立即购买
        sku_show(e){
            this.show = true
            this.getGoodsDetail(e)
        },
        //获取商品详细
        async getGoodsDetail(e){
            let form = {
                id:e,
                openid:this.openid
            }
            this.sku_loading = true
            let {data:{code,data},} = await this.$http.get(this.$api.goodsList,form)
            this.sku_loading = false
            if (code === 0) {
                let sku_list = data.gui.map((item) => {
                    if (item[0].m_price) {
                        if (JSON.parse(item[0].m_price) instanceof Array) {
                            item[0].count =JSON.parse(item[0].m_price)[0].num;
                        }else{
                            item[0].count = 1
                        }
                    }else{
                        item[0].count = 1
                    }
                    
                    item[0].price = item[0].price || JSON.parse(item[0].m_price);
                    return item[0];
                });
                let good = data.items[0]
                this.sku = {
                    ...{logo:data.log[0].url},
                    sku_list,
                    good
                }
                this.curr_sku = this.sku.sku_list[0]
                this.skuId = this.curr_sku.id
                console.log('this.sku>>>>>>>>>>>>>>>>',this.sku)
                console.log('this.curr_sku>>>>>>>>>>>>>>>>',this.curr_sku)
            }
        },
        //数组排序
		compare(property){
			return function(a,b){
				var value1 = a[property];
				var value2 = b[property];
				return value1 - value2;
			}
		},
        //加入购物车
        async shopcartAdd() {
            console.log('加入购物车')
            let form = {
                goods_id: this.sku.good.id,
				num: this.curr_sku.count,
				hao_id: this.curr_sku.id,
                openid: this.openid,
                price:Array.isArray(this.curr_sku.price)?Number(this.curr_sku.price[this.curr_sku.price.length-1].price):this.curr_sku.price
                
            }
            this.btn_loading = true
            let{data:{code,data}} = await this.$http.post(this.$api.cartIncrease,form)
            this.btn_loading = false
            if (code === 0) {
                this.show = false
                this.$toast.success(data);
            }
        },
        //立即购买
        buy() {
            console.log('立即购买')
            let nowPrice = this.curr_sku.price
            if (this.curr_sku.price instanceof Array) {
                nowPrice = this.curr_sku.price[0].price
                this.curr_sku.price.forEach(item=>{
                    if (this.curr_sku.count>=Number(item.num)) {
                        nowPrice = item.price
                    }
                })
            }
            let data = {
				title: this.sku.good.title,
				goods_id: this.sku.good.id,
				guageId: this.curr_sku.id,
				guageName: this.curr_sku.name,
				price: nowPrice,
				num: this.curr_sku.count,
                url: this.curr_sku.url,
                freight:this.sku.good.freight
            }
            console.log(data)
			this.$store.commit('payGoods', data)
			this.$router.push('/orderconfirmNow')
        },
        //切换菜单
        changeMenu(value){
            console.log(value)
            this.getList()
        },
        //获取列表
        async getList(){
            let form={
                sort: this.good_sort,
                class_name: this.good_stype,
                size: 1000,
                current: 1,
                openid: this.openid,
            }
            this.loading = true
            let {data:{code,data}} = await this.$http.get(this.$api.IndexGetData,form)
            let {data:{data:{items:logoArr}}} = await this.$http.get(this.$api.goodslog,form)
            this.loading = false
            if (code === 0) {
                this.good_list = data.items.map((item, index) => {
                    item.logoUrl = logoArr[index].url;
                    if (item.m_price) {
                        if (JSON.parse(item.m_price) instanceof Array ) {
                            item.m_price = JSON.parse(item.m_price).sort(this.compare('num'))
                        }else{
                            item.m_price = JSON.parse(item.m_price)
                        }
                    }else{
                        item.m_price = Number(item.price)
                    }
                    
                    return item;
                });
                console.log('商品列表>>>>>>>>>>>>>>>>',this.good_list)
            }
        },
        //下拉刷新
        onRefresh(){
            this.getList()
            this.isLoading = false
        },
        //登录
        login(){
            if (localStorage.getItem("openId")) {
                this.$store.commit("setOpenId", localStorage.getItem("openId"));
                this.getUserInfo();
                this.isLoading = false
            } else {
                if (!GetQueryString("code")) {
                    //let currentUrl = encodeURIComponent(window.location.href)
                    let currentUrl = encodeURIComponent(process.env.VUE_APP_BASE_URL);
                    window.location.href ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+process.env.VUE_APP_APPID+"&redirect_uri=" + currentUrl +"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                } else {
                    let code = GetQueryString("code");
                    let state = GetQueryString("state");
                    this.getWeixinOpenID(code, state);
                    
                    this.isLoading = false
                }
            }
        },
        //获取用户信息
        async getUserInfo() {
            let form={
                openid:this.openid
            }
            let {data: { code, data },} = await this.$http.get(this.$api.userinfo,form);
            if (code === 0) {
                localStorage.setItem("userState", data.userinfo.state);
                this.$store.commit("userState", localStorage.getItem("userState"));
                this.getList()
            }
        },
        //获取用户openid
        async getWeixinOpenID(UrlCode, state) {
            let form={
                code:UrlCode,
                state
            }
            let {data: { code, data },} = await this.$http.get(this.$api.accesstoken,form);
            if (code == 0) {
                localStorage.setItem("openId", data.openid);
                this.$store.commit("setOpenId", localStorage.getItem("openId"));
                this.getUserInfo();
            }
        },
    }
}
</script>
<style lang="scss" scoped>
    .index{
        .banner{
            .my-swipe{
                img{
                    width: 100%;
                }
            }
        }
        .van-skeleton__content{
            margin-top: 2rem;
        }
        .van-skeleton__row, .van-skeleton__title{
            background-color: #fff;
        }
        .list{
            padding:1rem 0 50px 0;
            
            .item{
                .van-card{
                    background-color: #fff;
                }
                .goodimg{
                    margin: 0.5rem 0;
                    img{
                        width: 100%;
                    }
                }
                margin-bottom: 1rem;
            }
        }
        .custom-image .van-empty__image {
            width: 90px;
            height: 90px;
        }
        .cont{
            padding: 2rem 0 3rem 0;
            .sku_header{
                padding: 1rem;
                display: flex;
                .img{
                    img{
                        width: 10rem;
                        height: 10rem;
                    }
                }
                .sku_goodsinfo{
                    margin-left: 1rem;
                    .goods_price{
                        display: flex;
                        span{
                            font-size: 16px;
                            color: red;
                        }
                        .goods_price_item{
                            padding: 0.2rem 0.5rem;
                            text-align: center;
                            h3{
                                font-size: 16px;
                                color: red;
                            }
                            p{
                                font-size: 12px;
                            }
                        }
                    }
                    .goods_item{
                        padding: 0.5rem 0;
                        font-size: 12px;
                        color: #999;
                    }
                }
            }
            .goods_body{
                margin-bottom: 50px;
                .goods_num{
                    display: flex;
                    justify-content: space-between;
                    .title{
                        padding: 1rem 0;
                    }
                }
            }
            .goods_body{
                padding: 1rem;
                .btm{
                    display: flex;
                    flex-wrap: wrap;
                    padding: 1rem 0;
                    .item{
                        padding: 0.5rem 1rem;
                        margin-right: 0.5rem;
                        margin-bottom: 0.5rem;
                        background-color: #f0f0f0;
                        font-size: 14px;
                    }
                    .current{
                        color: #fff;
                        background-color: red;
                    }
                }

            }
        }
        .popup{
            min-height: 54vh;
            .van-skeleton__row, .van-skeleton__title{
                background-color: #f0f0f0;
            }
        }
        
    }
</style>